package com.situ.mymall.interceptor;


import com.situ.mymall.pojo.entity.Admin;
import com.situ.mymall.pojo.entity.User;
import com.situ.mymall.service.IAdminService;
import com.situ.mymall.service.IUserService;
import com.situ.mymall.service.impl.AdminServiceImpl;
import com.situ.mymall.service.impl.UserServiceImpl;
import com.situ.mymall.util.CookieUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;


//拦截器
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户有没有登录
        //2.如果登录了，就放行，可以正常访问后台资源
        //3.如果没有登录，跳转到登录界面
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        //账号密码在Cookie中找不到
        if (admin == null){

            //自动登录
            Cookie cookie = CookieUtils.getCookie(request, "autoLogin");
            if (cookie != null){

                String[] values = cookie.getValue().split("&");
                String name = values[0];
                String password = values[1];
                IAdminService adminService = new AdminServiceImpl();
                admin = adminService.login(name,password);
                if (admin != null){
                    session.setAttribute("admin",admin);
                    //已经登录，放行
                    return true;
                }
            }

            //没有登录，跳转到登录界面
            response.sendRedirect("/page/login");
            return false;
        }
        //已经登录，放行
        return true;
    }
}
